<template>
    <div class="dropdown-panel" :style="{ width: props.width }" @keydown="handleKeyDown" tabindex="0">
        <div class="search" ref="searchPanel">
            <el-input v-model="searchKeyword" placeholder="请输入" :suffix-icon="Search"/>
        </div>
        <div class="options" :style= "{ maxHeight: props.opMaxHeight }" ref="optionsPanel">
            <div :class="['item',selectedIndex===index? 'is_select' : '']" v-for="( option , index ) in filteredOptions" :key="option.id"
                @click="selectOption(option, props.index)" @mouseenter="handleMouseOver(index)">
                <el-text size="large">{{ option.label }}</el-text>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { Search } from '@element-plus/icons-vue';
const searchPanel = ref<HTMLElement | null>(null);
const optionsPanel = ref<HTMLElement | null>(null);
let $emit = defineEmits(['selectOption']);
//处理键盘事件
const selectedIndex = ref(-1); // 表示当前选中项的索引，默认为-1
const handleKeyDown = (event: KeyboardEvent) => {
    if (event.key === 'ArrowDown') {
        // 阻止事件冒泡
        event.preventDefault();
        moveSelection(1); // 向下移动
    } else if (event.key === 'ArrowUp') {
        // 阻止事件冒泡
        event.preventDefault();
        moveSelection(-1); // 向上移动
    } else if (event.key === 'Enter') {
        // 阻止事件冒泡
        event.preventDefault();
        selectOption(filteredOptions.value[selectedIndex.value],props.index); // 回车选中
    };
};
const moveSelection = (direction: number) => {
    if(!optionsPanel.value){
        return;
    }

    // 处理滚动条事件
    if ((direction > 0 && selectedIndex.value >= maxIndex) || (direction < 0 && selectedIndex.value <= 0)) {
        return;
    } else{
        // 更新选中项的索引逻辑
        selectedIndex.value += direction;        
    }
    if (direction > 0 && selectedIndex.value*38 + 38  > optionsPanel.value.scrollTop + opHeight ) {            
        optionsPanel.value.scrollTop = Math.round(optionsPanel.value.scrollTop + 38);
    } else if (direction < 0 && selectedIndex.value*38 < optionsPanel.value.scrollTop) {
        optionsPanel.value.scrollTop = Math.round(optionsPanel.value.scrollTop - 38);
    }    
};
const handleMouseOver = (index:number) => {    
    selectedIndex.value = index;
};

export interface Option {
    id: string;
    label: string;
}

const props = defineProps({
    width: {
        type: String,
        default: "200px"
    },
    opMaxHeight:{
        type: String,
        default: "310px"
    },
    options: {
        type: Object,
        default: ""
    },
    index: {
        type: Number,
        default: 0
    }
})
const opHeight = parseInt(props.opMaxHeight);
const searchKeyword = ref('');
let maxIndex:number;
const filteredOptions = computed(() => {
    const  filterOptions = props.options.filter((option: Option) =>
        option.label.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );    
    maxIndex = filterOptions.length - 1;
    selectedIndex.value=-1;
    return filterOptions;
});


const selectOption = (option: Option, parentIndex: number) => {
    // 处理选中逻辑  
    if (parentIndex >= 0) {
        $emit('selectOption', { option: option, parentIndex: parentIndex })
    } else {
        $emit('selectOption', { option: option })
    }      
};
onMounted(() => {
    // 在组件打开时设置焦点,获取焦点
    const searchInput = searchPanel.value?.querySelector('input');
    if(searchInput){
        const searchInputFucos = () => {
            nextTick(() => {
                searchInput.focus();
            });      
        };
        searchInputFucos();
    }
    // document.addEventListener('keydown', handleKeyDown);
});
onUnmounted(() => {
    // document.removeEventListener('keydown', handleKeyDown);
});

</script>

<style scoped>
.dropdown-panel {
    min-height: 200px;
    position: absolute;
    background-color: var(--el-bg-color-overlay);
    border-radius: 4px;
    border: 0.5px solid var(--el-border-color-lighter);
    box-shadow: 8px 8px 10px rgba(0, 0, 0, 0.2);
    .search {
        margin: 15px 20px 0 20px;
    }

    .options {
        margin: 10px;        
        overflow-y: auto;

        .item {
            display: flex;
            align-items: center;
            height: 38px;
            padding: 10px 0 10px 15px;
            border-radius: 4px;          
        }
        .is_select {
            background-color: var(--el-color-info-light-8);
            cursor: pointer;
        }
    }
}
</style>